<template>
  <div class="app-container">
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="postForm" :model="postForm" label-width="100px">
        <div>
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="postForm.title" style="width:300px" />
          </el-form-item>
          <el-form-item label="图片" style="clear:both">
            <el-upload
              class="avatar-uploader"
              :action="this.$http.defaults.baseURL+'api/mpfile/upload/'"
              :show-file-list="false"
              :on-success="handleSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              :headers="myHeaders"
              accept="image/jpeg,image/png,image/gif"
            >
              <img v-if="imgFileId" :src="this.$http.defaults.baseURL+'api/mpfile/download?id='+parseInt(imgFileId)" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="刊登天数" prop="dayNum">
            <el-input-number v-model="postForm.dayNum" :min="1" />
          </el-form-item>
          <el-form-item style="margin-bottom: 30px;">
            <el-button type="primary" :loading="btnLoading" @click="submit">提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="标题" style="width: 200px; margin-right: 10px;" clearable />
      <el-select v-model="listQuery.status" placeholder="状态" style="width: 200px; margin-right: 10px;" clearable>
        <el-option v-for="item in statusOptions" :key="'status_' + item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" @click="getList()">搜索</el-button>
      <el-button @click="resetSearchForm()">重置</el-button>
      <el-button class="filter-item" style="margin-left: 10px;float:right" type="success" icon="el-icon-edit" @click="addnew">
        新建
      </el-button>
    </div>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" prop="id" label="编号" width="80" />
      <el-table-column prop="title" label="标题" show-overflow-tooltip />
      <el-table-column align="center" prop="publishTime" label="开始刊登时间" width="160" />
      <el-table-column align="center" prop="dayNum" label="刊登天数" width="100" />
      <el-table-column align="center" prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">未刊登</span>
          <span v-if="scope.row.status === 1" style="color: green;">刊登中</span>
          <span v-if="scope.row.status === 2" style="color: red;">已过期</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" @click="showpic(scope.row.fileId)">
            查看图片
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" @click="edit(scope.row)">
            编辑
          </el-button>
          <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

export default {
  name: 'SloganList',
  components: { Pagination },
  data() {
    return {
      dialogtitle: '新增',
      dialogVisible: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: '',
        status: ''
      },
      btnLoading: false,
      imgFileId: null,
      postForm: {
        id: null,
        title: '',
        dayNum: 1
      },
      statusOptions: [
        { label: '刊登中', value: 1 },
        { label: '已过期', value: 2 }
      ],
      myHeaders: {}
    }
  },
  created() {
    this.getList()
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
  },
  methods: {
    // 获取列表
    getList() {
      const para = {
        pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit,
        title: this.listQuery.title,
        status: this.listQuery.status,
        postId: 1
      }
      this.listLoading = true
      this.$http
        .post('/api/busAdvertXcx/queryByPage', para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result.records
            this.total = response.data.result.total
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.listQuery.page = response.data.result.pages
              this.getList()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
    },
    // 重置
    resetSearchForm() {
      this.listQuery.title = ''
      this.listQuery.status = ''
      this.getList()
    },
    // 新建
    addnew() {
      this.postForm.id = null
      this.postForm.title = ''
      this.postForm.dayNum = 1
      this.imgFileId = null
      this.dialogtitle = '新增'
      this.dialogVisible = true
    },
    // 提交
    submit() {
      const para = {}
      para.id = this.postForm.id
      para.title = this.postForm.title
      para.dayNum = this.postForm.dayNum
      para.fileId = this.imgFileId
      para.postId = 1
      if (!para.title) {
        this.$message({
          message: '请填写标题',
          type: 'error'
        })
        return
      }
      if (!para.fileId) {
        this.$message({
          message: '请上传图片',
          type: 'error'
        })
        return
      }
      this.btnLoading = true
      this.$http
        .post('/api/busAdvertXcx/save', para)
        .then(response => {
          this.btnLoading = false
          if (response.data.success === true) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            })
            this.dialogVisible = false
            this.getList()
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.btnLoading = false
        })
    },
    // 查看图片
    showpic(id) {
      console.log('baseURL')
      console.log(this.$http.defaults.baseURL)
      window.open(this.$http.defaults.baseURL + 'api/mpfile/download?id=' + id)
    },
    // 编辑
    edit(row) {
      console.log(row)
      this.postForm.id = row.id
      this.postForm.title = row.title
      this.postForm.dayNum = row.dayNum
      this.imgFileId = row.fileId
      this.dialogtitle = '编辑'
      this.dialogVisible = true
    },
    // 删除
    deleteData(id) {
      let ids = []
      if (id) {
        ids = [id]
      }
      if (ids.length > 0) {
        this.$http
          .post('/api/busAdvertXcx/remove', { ids: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    // 上传图片
    handleSuccess(response, file, fileList) {
      if (response.success) {
        this.btnLoading = false
        const obj = response.result[0]
        this.imgFileId = obj.id
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
        this.btnLoading = false
      }
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isAllowedType = ['image/png', 'image/jpeg', 'image/jpg', 'image/bmp'].includes(file.type)
      if (!isImage || !isAllowedType) {
        this.$message.error('只能上传PNG、JPG、JPEG和BMP格式的图片文件!')
        return false
      }
      const isLt500M = file.size / 1024 / 1024 < 500
      if (!isLt500M) {
        this.$message.error('单个附件不能超过500M!')
        return false
      } else {
        this.btnLoading = true
      }
      return isLt500M && isImage && isAllowedType
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
      this.btnLoading = false
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
